<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="80%"
  >
    <el-row>
      <el-col :span="15">
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          label-width="90px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="图标框图:" prop="icon">
                <div class="myhead">
                  <el-tooltip content="点击上传图标" placement="top">
                    <el-image
                      style="width: 90px; height: 60px"
                      :src="
                        dataForm.icon +
                          '?x-oss-process=image/resize,h_100,w_100'
                      "
                      fit="contain"
                      @click="uploadIconbHandle"
                      alt=""
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="缩略图:" prop="thumb">
                <div class="myhead">
                  <el-tooltip content="点击上传缩略图" placement="top">
                    <el-image
                      style="width: 90px; height: 60px"
                      :src="
                        dataForm.thumb +
                          '?x-oss-process=image/resize,h_100,w_100'
                      "
                      fit="contain"
                      @click="uploadThumbHandle()"
                      alt=""
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="锁屏壁纸:" prop="screen">
                <div class="myhead">
                  <el-tooltip content="点击上传锁屏壁纸" placement="top">
                    <el-image
                      style="width: 90px; height: 60px"
                      :src="
                        dataForm.screen +
                          '?x-oss-process=image/resize,h_100,w_100'
                      "
                      fit="contain"
                      @click="uploadScreenHandle()"
                      alt=""
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="桌面壁纸:" prop="desktop">
                <div class="myhead">
                  <el-tooltip content="点击上传桌面壁纸" placement="top">
                    <el-image
                      style="width: 90px; height: 60px"
                      :src="
                        dataForm.desktop +
                          '?x-oss-process=image/resize,h_100,w_100'
                      "
                      fit="contain"
                      @click="uploadDesktopHandle()"
                      alt=""
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="主题附件:" prop="fileUrl">
                <div class="myhead">
                  <el-tooltip content="点击上传图标ZIP文件附件" placement="top">
                    <el-image
                      style="width: 80px; height: 50px"
                      :src="
                        dataForm.attachmentpic +
                          '?x-oss-process=image/resize,h_100,w_100'
                      "
                      fit="contain"
                      @click="uploadAttachment()"
                      alt=""
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="附件名:" prop="fileUrl">
                <div class="text item">
                  {{ dataForm.fileName }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="主题名称" prop="name">
                <el-input
                  v-model="dataForm.name"
                  placeholder="主题名称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="是否上架:" prop="status">
                <el-select
                  v-model="dataForm.status"
                  filterable
                  placeholder="请选择是否上架"
                  size="medium"
                >
                  <el-option
                    v-for="item in statusList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="是否免费:" prop="free">
                <el-select
                  v-model="dataForm.free"
                  filterable
                  placeholder="请选择是否免费"
                  size="medium"
                >
                  <el-option
                    v-for="item in freeList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="15">
              <el-form-item label="是否热门:" prop="hot">
                <el-select
                  v-model="dataForm.hot"
                  filterable
                  placeholder="请选择是否热门"
                  size="medium"
                >
                  <el-option
                    v-for="item in hotList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="15">
              <el-form-item label="是否最新:" prop="newest">
                <el-select
                  v-model="dataForm.newest"
                  filterable
                  placeholder="请选择是否最新"
                  size="medium"
                >
                  <el-option
                    v-for="item in newestList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="15">
              <el-form-item label="主题分类:" prop="classifyId">
                <el-select
                  v-model="dataForm.classifyId"
                  filterable
                  placeholder="请选择所属分类类"
                  size="medium"
                  @change="onSelectType"
                >
                  <el-option
                    v-for="item in itemsCatList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="主题标签" prop="labels">
                <el-input
                  v-model="dataForm.label"
                  placeholder="主题标签(回车键确定)"
                  @keyup.enter.native="addLabels()"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="" prop="label">
                <el-tag
                  :key="tag"
                  v-for="tag in dataForm.labels"
                  closable
                  :disable-transitions="false"
                  @close="removeLabels(tag)"
                >
                  {{ tag }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="10">
              <el-form-item label="主题描述:" prop="describes">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 3 }"
                  placeholder="主题描述"
                  v-model="dataForm.describes"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="15">
              <el-form-item label="上传按钮:" prop="upload">
                <div class="myhead">
                  <el-tooltip content="点击上传预览图" placement="top">
                    <el-image
                      style="width: 90px; height: 60px"
                      :src="dataForm.upload"
                      fit="contain"
                      @click="uploadImagesHandle"
                      alt=""
                    />
                  </el-tooltip>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="15">
              <el-form-item label="预览展示:" prop="images">
                <div
                  class="demo-image"
                  v-for="(item, index) in dataForm.images"
                  :key="index"
                >
                  <el-image
                    style="width: 50px; height: 100px"
                    :src="item"
                    fit="contain"
                  >
                  </el-image>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
      <el-col :span="9">
        <div style="position: relative;">
          <div class="bg-phone-left">
            <div
              :class="{ 'tab-left-active': activePic == 1, 'tab-left': true }"
              @click="changeactivePic(1)"
            >
              锁屏
            </div>
            <div
              :class="{ 'tab-left-active': activePic == 2, 'tab-left': true }"
              @click="changeactivePic(2)"
            >
              桌面
            </div>
          </div>
          <div class="bg-phone">
            <div class="bg-phone-content">
              <img
                :src="dataForm.screen"
                v-show="activePic == 1"
                style="width:100%;height:auto"
              />
              <img
                :src="dataForm.desktop"
                v-show="activePic == 2"
                style="width:100%;height:auto"
              />
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <!-- 弹窗, 上传图标框 -->
    <theme-upload-icon
      v-if="uploadIconVisible"
      ref="themeUploadIcon"
      @refreshDataList="refreshUploadIcon"
    ></theme-upload-icon>
    <!-- 弹窗, 上传缩略图 -->
    <theme-upload-thumb
      v-if="uploadThumbVisible"
      ref="themeUploadThumb"
      @refreshDataList="refreshUploadThumb"
    ></theme-upload-thumb>
    <!-- 弹窗, 上传详情图2 -->
    <theme-upload-screen
      v-if="uploadScreenVisible"
      ref="themeUploadScreen"
      @refreshDataList="refreshUploadScreen"
    ></theme-upload-screen>
    <!-- 弹窗, 上传详情图2 -->
    <theme-upload-desktop
      v-if="uploadDesktopVisible"
      ref="themeUploadDesktop"
      @refreshDataList="refreshUploadDesktop"
    ></theme-upload-desktop>
    <!-- 弹窗, 上传附件 -->
    <theme-upload-attachment
      v-if="uploadAttachmentVisible"
      ref="themeUploadAttachment"
      @refreshDataList="refreshAttachmentUrl"
    ></theme-upload-attachment>
    <!-- 弹窗, 上传多张详情图 -->
    <theme-upload-images
      v-if="uploadImagesVisible"
      ref="themeUploadImages"
      @refreshDataList="refreshUploadImages"
    ></theme-upload-images>
  </el-dialog>
</template>

<script>
import "babel-polyfill";
// 上传图标框
// 上传缩略图
// 上传锁屏壁纸
// 上传详桌面壁纸
import ThemeUploadIcon from "./theme-upload-image";
import ThemeUploadThumb from "./theme-upload-image";
import ThemeUploadScreen from "./theme-upload-image";
import ThemeUploadDesktop from "./theme-upload-image";
import ThemeUploadImages from "./theme-upload-images";
import ThemeUploadAttachment from "./theme-upload-attachment";

export default {
  data() {
    return {
      // 选择展示层级
      activePic: 1,
      visible: false,
      statusList: [
        {
          value: 1,
          name: "是"
        },
        {
          value: 2,
          name: "否"
        }
      ],
      freeList: [
        {
          value: 1,
          name: "免费"
        },
        {
          value: 2,
          name: "VIP+视频"
        },
        {
          value: 3,
          name: "仅VIP"
        },
        {
          value: 4,
          name: "仅视频"
        }
      ],
      hotList: [
        {
          value: 1,
          name: "是"
        },
        {
          value: 2,
          name: "否"
        }
      ],
      newestList: [
        {
          value: 1,
          name: "是"
        },
        {
          value: 2,
          name: "否"
        }
      ],
      itemsCatList: [],
      uploadIconVisible: false,
      uploadThumbVisible: false,
      uploadScreenVisible: false,
      uploadDesktopVisible: false,
      uploadAttachmentVisible: false,
      uploadImagesVisible: false,
      dataForm: {
        id: 0,
        name: "",
        price: "",
        classifyId: "",
        classifyName: "",
        describes: "",
        free: 1,
        hot: 2,
        newest: 2,
        status: 2,
        icon: "http://file-cdn-theme.cykonhy.com/default/default.jpg",
        thumb: "http://file-cdn-theme.cykonhy.com/default/default.jpg",
        screen: "http://file-cdn-theme.cykonhy.com/default/default.jpg",
        desktop: "http://file-cdn-theme.cykonhy.com/default/default.jpg",
        attachmentpic:
          "http://file-cdn-theme.cykonhy.com/default/attachment.jpg",
        fileName: "",
        fileUrl: "",
        images: [],
        upload: "http://file-cdn-theme.cykonhy.com/default/upload_icon.png", //不用上传和提交
        image: "http://file-cdn-theme.cykonhy.com/default/default.jpg", //不用上传和提交
        label: "",
        labels: []
      },
      dataRule: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        classifyId: [
          { required: true, message: "分类Id不能为空", trigger: "blur" }
        ],
        describes: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        upload: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        images: [{ required: true, message: "壁纸不能为空", trigger: "blur" }],
        labels: [{ required: true, message: "标签不能为空", trigger: "blur" }],
        free: [
          { required: true, message: "是否免费不能为空", trigger: "blur" }
        ],
        hot: [{ required: true, message: "是否热门不能为空", trigger: "blur" }],
        newest: [
          { required: true, message: "是否最新不能为空", trigger: "blur" }
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      }
    };
  },
  components: {
    ThemeUploadIcon,
    ThemeUploadThumb,
    ThemeUploadScreen,
    ThemeUploadDesktop,
    ThemeUploadAttachment,
    ThemeUploadImages
  },
  methods: {
    changeactivePic(val) {
      this.activePic = val;
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/theme/theme/info/${this.dataForm.id}`),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.userId = data.theme.userId;
              this.dataForm.name = data.theme.name;
              this.dataForm.classifyId = data.theme.classifyId;
              this.dataForm.classifyName = data.theme.classifyName;
              this.dataForm.icon = data.theme.icon;
              this.dataForm.thumb = data.theme.thumb;
              this.dataForm.images = data.theme.images;
              this.dataForm.labels = data.theme.labels;
              this.dataForm.free = data.theme.free;
              this.dataForm.hot = data.theme.hot;
              this.dataForm.newest = data.theme.newest;
              this.dataForm.status = data.theme.status;

              this.dataForm.screen = data.theme.screen;
              this.dataForm.desktop = data.theme.desktop;
              this.dataForm.fileName = data.theme.fileName;
              this.dataForm.fileUrl = data.theme.fileUrl;
              this.dataForm.describes = data.theme.describes;
              this.dataForm.status = data.theme.status;
              this.dataForm.created = data.theme.created;
              this.dataForm.updated = data.theme.updated;
            }
          });
        }
      });
      this.initItemCat();
    },
    initItemCat() {
      this.$http({
        url: this.$http.adornUrl("/theme/theme-classify/list"),
        method: "get",
        params: this.$http.adornParams({
          page: 1,
          limit: 10000
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.itemsCatList = data.page.list;
        }
      });
    },
    // 筛选类型
    onSelectType(val) {
      let obj = this.itemsCatList.find(item => {
        return item.id === val;
      });
      this.dataForm.classifyName = obj.name;
    },
    // 上传图标框
    uploadThumbHandle() {
      this.uploadThumbVisible = true;
      this.$nextTick(() => {
        this.$refs.themeUploadThumb.init();
      });
    },
    refreshUploadThumb(filePath) {
      if (filePath != "") {
        this.dataForm.thumb = filePath;
      }
      this.uploadThumbVisible = false;
    },

    // 上传缩略图
    uploadIconbHandle() {
      this.uploadIconVisible = true;
      this.$nextTick(() => {
        this.$refs.themeUploadIcon.init();
      });
    },
    refreshUploadIcon(filePath) {
      if (filePath != "") {
        this.dataForm.icon = filePath;
      }
      this.uploadIconVisible = false;
    },
    // 上传锁屏壁纸
    uploadScreenHandle() {
      this.uploadScreenVisible = true;
      this.$nextTick(() => {
        this.$refs.themeUploadScreen.init();
      });
    },
    refreshUploadScreen(filePath) {
      if (filePath != "") {
        this.dataForm.screen = filePath;
      }
      this.uploadScreenVisible = false;
    },

    // 上传锁桌面壁纸
    uploadDesktopHandle() {
      this.uploadDesktopVisible = true;
      this.$nextTick(() => {
        this.$refs.themeUploadDesktop.init();
      });
    },
    refreshUploadDesktop(filePath) {
      if (filePath != "") {
        this.dataForm.desktop = filePath;
      }
      this.uploadDesktopVisible = false;
    },

    // 上传附件
    uploadAttachment() {
      this.uploadAttachmentVisible = true;
      this.$nextTick(() => {
        this.$refs.themeUploadAttachment.init();
      });
    },
    refreshAttachmentUrl(fileList) {
      if (fileList.length > 0) {
        this.dataForm.fileName = fileList[0].name;
        this.dataForm.fileUrl = fileList[0].url;
      }
      this.uploadAttachmentVisible = false;
    },

    // 上传多张详情图
    uploadImagesHandle() {
      this.uploadImagesVisible = true;
      this.$nextTick(() => {
        this.$refs.themeUploadImages.init();
      });
    },
    refreshUploadImages(images) {
      if (images != null && images.length > 0) {
        this.dataForm.image = images[0];
        this.dataForm.images = images;
      }
      this.uploadImagesVisible = false;
    },

    addLabels() {
      this.dataForm.labels.push(this.dataForm.label);
      this.dataForm.label = "";
    },
    removeLabels(tag) {
      //1、获取元素下标
      let delete_index = this.getArrayIndex(this.dataForm.labels, tag);
      //2、删除指定元素下标；
      let tempLabels = [];
      for (let i = 0, len = this.dataForm.labels.length; i < len; i++) {
        if (i != delete_index) {
          tempLabels.push(this.dataForm.labels[i]);
        }
      }
      this.dataForm.labels = [];
      this.dataForm.labels = tempLabels;
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          let itemPrice = this.regYuanToFen(this.dataForm.price, 100);
          this.$http({
            url: this.$http.adornUrl(
              `/theme/theme/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              userId: this.dataForm.userId,
              name: this.dataForm.name,
              classifyId: this.dataForm.classifyId,
              classifyName: this.dataForm.classifyName,
              icon: this.dataForm.icon,
              thumb: this.dataForm.thumb,
              images: this.dataForm.images,
              labels: this.dataForm.labels,
              screen: this.dataForm.screen,
              desktop: this.dataForm.desktop,
              fileName: this.dataForm.fileName,
              fileUrl: this.dataForm.fileUrl,
              describes: this.dataForm.describes,
              free: this.dataForm.free,
              hot: this.dataForm.hot,
              newest: this.dataForm.newest,
              status: this.dataForm.status,
              created: this.dataForm.created,
              updated: this.dataForm.updated
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    /**
     * 分转化为元 - 正则解决精度
     * @param fen
     * @returns {boolean|string}
     */
    regFenToYuan(fen) {
      var num = fen;
      num = fen * 0.01;
      num += "";
      var reg =
        num.indexOf(".") > -1
          ? /(\d{1,3})(?=(?:\d{3})+\.)/g
          : /(\d{1,3})(?=(?:\d{3})+$)/g;
      num = num.replace(reg, "$1");
      num = this.toDecimal2(num);
      return num;
    },
    /**
     * 元转分 - 解决精度问题 yuan:要转换的钱，单位元； digit：转换倍数
     * @param yuan
     * @param digit
     * @returns {number}
     */
    regYuanToFen(yuan, digit) {
      var m = 0,
        s1 = yuan.toString(),
        s2 = digit.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {}
      try {
        m += s2.split(".")[1].length;
      } catch (e) {}
      return (
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
        Math.pow(10, m)
      );
    },
    toDecimal2(x) {
      var f = parseFloat(x);
      if (isNaN(f)) {
        return false;
      }
      var f = Math.round(x * 100) / 100;
      var s = f.toString();
      var rs = s.indexOf(".");
      if (rs < 0) {
        rs = s.length;
        s += ".";
      }
      while (s.length <= rs + 2) {
        s += "0";
      }
      return s;
    }
  }
};
</script>
<style scoped="scoped">
.text {
  font-size: 12px;
}
.item {
  margin-bottom: -20px;
}
.bg-phone {
  background: url("../../../assets/img/phone.png") no-repeat;
  background-size: 100%;
  width: 300px;
  height: 610px;
  padding: 50px 30px 30px 30px;
}
.bg-phone-content {
  /* background: #fff; */
  height: 560px;
  border-radius: 5px;
}
.bg-phone-left {
  position: absolute;
  left: -38px;
  top: 60px;
}
.tab-left {
  background: #dbdbdd;
  width: 50px;
  height: 30px;
  text-align: center;
  color: #fff;
  border-radius: 30px 0 0 30px;
  margin-bottom: 10px;
  line-height: 30px;
  cursor: pointer;
}
.tab-left-active {
  /* background: #17B3A3 !important;
    */
  background: #5175e6 !important;
}
</style>
